<template>
  <div>
    <el-card
      style="width: 99%; height: 100%; margin-left: 10px; margin-top: 10px"
      shadow="hover"
    >
      <!-- 表单标题 -->
      <div slot="header" class="card-header">
        <div>
          <span style="margin-right: 20px">个人资料管理</span>
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="toggleEdit"
            v-if="isloading"
            >编辑</el-button
          >
        </div>

        <el-button
          class="exit-btn"
          type="danger"
          plain
          @click="goBack"
          icon="el-icon-switch-button"
        >
          退出登录
        </el-button>
      </div>

      <!-- 表单内容 -->
      <el-form
        :model="userForm"
        :rules="rules"
        ref="userForm"
        label-width="100px"
        label-position="right"
        :disabled="isloading"
      >
        <!-- 头像上传 -->
        <el-form-item label="用户头像：" prop="avatar">
          <div class="avatar-container">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :http-request="customUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="userForm.avatar"
                :src="userForm.avatar"
                class="avatar"
              />
              <div v-else class="avatar-placeholder">
                <i class="el-icon-plus"></i>
                <p>点击上传头像</p>
              </div>
            </el-upload>
          </div>
        </el-form-item>

        <!-- 表单字段 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户类型：" prop="userType">
              <el-input v-model="userForm.userType" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名：" prop="username">
              <el-input v-model="userForm.username"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="真实姓名：" prop="realName">
              <el-input
                v-model="userForm.realName"
                :readonly="isloading"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱：" prop="email">
              <el-input
                v-model="userForm.email"
                :readonly="isloading"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机电话：" prop="phoneNumber">
              <el-input
                v-model="userForm.phoneNumber"
                :readonly="isloading"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学习方向：" prop="major">
              <el-input
                v-model="userForm.major"
                :readonly="isloading"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="QQ号码：" prop="qqNumber">
              <el-input
                v-model="userForm.qqNumber"
                :readonly="isloading"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="大学名字：" prop="university">
              <el-input
                v-model="userForm.university"
                :readonly="isloading"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="个人简介：" prop="userProfile">
          <el-input
            type="textarea"
            v-model="userForm.userProfile"
            :readonly="isloading"
            :autosize="{ minRows: 3, maxRows: 6 }"
          ></el-input>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="form-actions">
          <el-button type="primary" @click="submitForm" :loading="submitting"
            >保 存</el-button
          >
          <el-button @click="resetForm" style="margin-left: 100px"
            >取 消</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { reqGetUserInfo, reqUpdateUserInfo,reqUserLogout } from "@/api";

import { removeToken } from "@/utils/auth";
import axios from "axios";

export default {
  name: "Person",
  data() {
    return {
      isloading: true,
      submitting: false,
      // uploadUrl: "http://192.168.196.101:8081/api/upload",
      uploadUrl: "/api/upload",
      userForm: {
        userType: "",
        username: "",
        realName: "",
        email: "",
        major: "",
        qqNumber: "",
        phoneNumber: "",
        university: "",
        userProfile: "",
        avatar: "",
      },
      rules: {
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { type: "email", message: "请输入有效的邮箱地址", trigger: "blur" },
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入有效的手机号",
            trigger: "blur",
          },
        ],
        realName: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "姓名长度在2到10个字符",
            trigger: "blur",
          },
        ],
        userProfile: [
          { max: 200, message: "个人简介不超过200字", trigger: "blur" },
        ],
      },
      user: sessionStorage.getItem("userInfo")
        ? JSON.parse(sessionStorage.getItem("userInfo"))
        : {},
    };
  },
  created() {
    this.loadUserInfo();
  },
  methods: {
    customUpload(options) {
      const formData = new FormData();
      formData.append("file", options.file);

      axios
        .post(options.action, formData, {
          headers: {
            // "Content-Type": "multipart/form-data",
            Authorization: `Bearer ${sessionStorage.getItem("token")}`,
          },
        })
        .then((res) => {
          options.onSuccess(res.data);
        })
        .catch((err) => {
          options.onError(err);
        });
    },
    // 切换编辑模式
    toggleEdit() {
      this.isloading = false;
      this.$nextTick(() => {
        this.$refs.userForm.clearValidate();
      });
    },

    // 加载用户信息
    async loadUserInfo() {
      if (!this.user.sub) {
        this.$message.error("当前无法获取用户信息!请登录!");
        return;
      }

      try {
        this.loading = true;
        const res = await reqGetUserInfo();

        if (res.code === 200) {
          this.userForm = {
            ...this.userForm,
            ...res.data,
            avatar: res.data.avatar || require("@/assets/default-avatar.png"),
          };
          this.$message.success("信息加载成功" || res.message);
        }
      } catch (error) {
        this.$message.error("信息加载失败");
      } finally {
        this.loading = false;
      }
    },

    async goBack() {
      try {
        await this.$confirm("确定要退出系统吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        // 调用登出接口
        await reqUserLogout();

        // 清除本地token和用户信息
        removeToken();

        // 跳转到登录页
        this.$router.push("/login");
      } catch (error) {
        if (error !== "cancel") {
          this.$message.error(error.message || "登出失败");
        }
      }
    },

    // 表单提交
    submitForm() {
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          try {
            this.submitting = true;

            // 创建 userForm 副本并排除 userType
            const { userType, ...formData } = this.userForm; //利用解构赋值，提取想要的字段
            const res = await reqUpdateUserInfo(formData);

            if (res.code === 200) {
              this.$message.success("保存成功");
              this.isloading = true;
              this.loadUserInfo();
            } else {
              this.$message.error(res.msg || "保存失败");
            }
          } catch (error) {
            this.$message.error("提交失败，请重试");
          } finally {
            this.submitting = false;
          }
        }
      });
    },

    // 重置表单
    resetForm() {
      this.isloading = true;
      this.loadUserInfo();
      this.$refs.userForm.clearValidate();
    },

    // 头像上传成功
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.userForm.avatar = res.data;
        this.$message.success("头像上传成功");
      } else {
        this.$message.error(res.msg || "上传失败");
      }
    },

    // 上传前验证
    beforeAvatarUpload(file) {
      const isValidType = ["image/jpeg", "image/png", "image/gif"].includes(
        file.type
      );
      const isValidSize = file.size / 1024 / 1024 < 2;

      if (!isValidType) {
        this.$message.error("仅支持 JPG/PNG/GIF 格式!");
        return false;
      }

      if (!isValidSize) {
        this.$message.error("图片大小不能超过 2MB!");
        return false;
      }

      // 使用 FileReader 读取文件
      const reader = new FileReader();
      reader.onload = (e) => {
        this.userForm.avatar = e.target.result; // 将 Base64 赋值给 avatar
      };
      reader.readAsDataURL(file); // 读取文件为 DataURL

      return true;
    },

    // 自定义上传方法（可选）
    // customUpload(fileObj) {
    //   // 可在此处添加自定义上传逻辑
    //   // 默认使用action地址上传
    // }
  },
};
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.avatar-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  // position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s ease;
  &:hover {
    border-color: #409eff;
    background-color: #f5f7fa;
  }
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
  border-radius: 50%;
  // line-height: 150px;
  object-fit: cover; /* 保持图片比例填充容器 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.avatar-placeholder {
  width: 150px;
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #8c939d;
  font-size: 14px;
  text-align: center;
  transition: all 0.3s ease;

  &:hover {
    color: #409eff;
  }
}

.avatar-placeholder i {
  font-size: 32px;
  margin-bottom: 8px;
}

.form-actions {
  margin-top: 40px;
  // background-color: #409EFF;
  display: flex;
  justify-content: space-between;
}

::v-deep .el-form--disabled .el-form-item__content {
  opacity: 0.8;
}

@media (max-width: 768px) {
  .el-col-12 {
    width: 100%;
    margin-bottom: 15px;
  }
}
</style>
